package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayApiController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;

    //支付宝支付
    @ResponseBody
    @GetMapping("/submit/{orderId}")
    public String submit(@PathVariable Long orderId){
        return alipayService.submit(orderId);
    }


    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }

    @ResponseBody//必须以字符串返回，而不是跳转页面
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String,String> paramMap){
        //将异步通知中收到的所有参数存放到map中 签名，验签 防止掉包
        System.out.println(paramMap);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    paramMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
            if (signVerified){
                //二次校验  金额，交易号，金额等
                System.out.println("验签成功");
                if(paramMap.get("trade_status").equals("TRADE_SUCCESS")){
                    //交易成功--更新支付表
                    System.out.println("交易成功");
                    paymentService.updateStatus(paramMap);
                }else {
                    return "faliure";
                }
                return "success";
            }else {
                return "faliure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "faliure";
    }

    @ResponseBody
    @GetMapping("/refund/{outTradeNo}")
    public Result refund(@PathVariable String outTradeNo){
        alipayService.refund(outTradeNo);
        return Result.ok();
    }

}
